<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
	#div1 {width: 100px; height: 100px; line-height: 100px;text-align: center; color: #fff; background-color: red;position: absolute;left: 400px;top: 200px;}
	#target1 {width: 1px; height: 300px; background-color: #000;position: absolute;left: 400px;}
	#target2 {width: 1px; height: 300px; background-color: #000;position: absolute;left: 800px;}
	</style>
	<script type="text/javascript">
	window.onload = function (){
		var oBtn1 = document.getElementById('btn1');
		var oBtn2 = document.getElementById('btn2');
		var oDiv = document.getElementById('div1');

		oBtn2.onclick = function	(){
			doMove( oDiv, 800, 7 );
		}

		oBtn1.onclick = function	(){
			doMove( oDiv, 400, 7 );
		}
	}

	function doMove( obj, target, endFn ){
		//speed = obj.offsetLeft < target ? speed : -speed;
		//这句话可以省略了不需要判断了，因为下面的speed = ( target - obj.offsetLeft )/12已经可以判断符号了
		clearInterval( obj.timer );

		obj.timer = setInterval(function (){
			var speed = ( target - obj.offsetLeft )/12;
			speed = speed > 0 ? Math.ceil( speed ) : Math.floor( speed );

			var nextPos = obj.offsetLeft + speed;

			if ( nextPos > target && speed > 0 || nextPos < target && speed < 0 ) {
				nextPos == target;
			};

			obj.style.left = nextPos + 'px';
			obj.innerHTML = obj.style.left;

			if ( nextPos == target ) {
				clearInterval( obj.timer );
				endFn && endFn();
			};
		},30)
	}
	</script>
</head>
<body>
	<input id="btn1" type="button" value="向后移动" />
	<input id="btn2" type="button" value="向前移动" />
	<div id="div1"></div>
	<div id="target1"></div>
	<div id="target2"></div>
</body>
</html>